English 中文(简体)
在++中采用明确/标语
原标题:Using explicit/raw pointers in c++
  • 时间:2012-01-12 16:49:07
  •  标签:
  • c++
  • pointers

我读到,在C++中使用原始点器是坏的。 相反,我们应当使用<代码>auto_ptr<>/code>。 在以下代码中,我在<代码>foo()上填满了病媒,该文本在<代码>main(上创建。 我这样做是正确的,或者在不使用明确要点的情况下做得更好。

#include <iostream>
#include <vector>
#include <string>

using namespace std;

void foo(vector<string> *v){

    (*v).push_back(" hru");
}

int main(){
    vector<string> v;
    v.push_back("hi");
    foo(&v);
    for(int i=0;i<v.size(); i++){
        cout << v[i];
    }

}
最佳回答

C++在你试图做以下工作时使用参比<>>:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

void foo(vector<string>& v){
    v.push_back(" hru");
}

int main(){
    vector<string> v;
    v.push_back("hi");
    foo(v);
    for(int i=0;i<v.size(); i++){
        cout << v[i];
    }
}

参考资料和点数类似,有一个非常重要的区分:没有这样的东西,即null reference(

问题回答

在C++中,你可以避免点子,并采用逐项参照:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

void foo(vector<string>& v){

    v.push_back(" hru");
}

int main(){
    vector<string> v;
    v.push_back("hi");
    foo(v);
    for(int i=0;i<v.size(); i++){
        cout << v[i];
    }    
}




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签