2016-04-26 124 views
0
//prototype  
void Split(char c, vector <MyString> &outputVector) const   

//partial code inside split function 
// create new MyString object to push into output vector 
MyString substr; 
substr.mString = newString; 
substr.mLength = size; 

// push new item 
outputVector.push_back(substr); 

当我跨过outputVector.push_back()行后,mString数据成员不会保留。push_back结构化为向量

//I have two constructors 
MyString() 
{ 
    mString = NULL; 
    mLength = 0; 
} 

/************************************************* 
* MyList copy constructor 
* creates a deep copy of a MyString item 
************************************************/ 
MyString(const MyString &copy) 
{ 
    mString = new char[copy.mLength]; 
    int i; 

    for(; i < copy.mLength; i++) 
    { mString[i] = copy.mString[i]; } 

    mString[i] = '\0'; 
    mLength = copy.mLength; 

} 

enter image description here

+6

欢迎来到堆栈溢出!请** [编辑] **您的问题用[mcve]或[SSCCE(Short,Self Contained,Correct Example)](http://sscce.org) – NathanOliver

+1

向我们展示'MyString'的定义 –

+2

You * do *遵循[MyString'类的[三,五或零规则](http://en.cppreference.com/w/cpp/language/rule_of_three))?有没有原因你不使用标准的'std :: string'类? –

回答

6

您使用的是未初始化的变量是undefined behavior

int i; 

for(; i < copy.mLength; i++) 

在这里,我们不知道什么i是这样什么都可以去上,但最有可能的i大于copy.mLength,所以我们永远不会进入for循环。为了得到正确的行为设置i 0喜欢

int i = 0; 

您有

mString[i] = '\0'; 

另一个问题,当我们到达该行的时间i == copy.mLength但数组仅有的copy.mLength的大小,所以我们都由于数组是基于0索引的,所以最后一个结束。最有可能你需要改变你的分配

mString = new char[copy.mLength + 1]; 

给你空间的空终止符。

+0

这完全解决了它!谢谢! –

0

http://www.cplusplus.com/reference/vector/vector/push_back/

的push_back副本值向量。 MyString类是否有正确定义的拷贝构造函数,拷贝mString成员?我想这可能是你的问题。

+1

答案不应该是一个猜测。既然OP实际上提供了代码,你可以看到他们有一个拷贝构造函数,但它有UB。 – NathanOliver

+0

对不起 - 在提供完整代码之前发布的答案。 –

-1

拷贝构造函数的正确版本

MyString(const MyString &copy) 
{ 
    mString = new char[copy.mLength + 1]; 
    int i = 0; 

    for(; i < copy.mLength; i++) 
    { mString[i] = copy.mString[i]; } 

    mString[i] = '\0'; 
    mLength = copy.mLength; 

} 
+0

反对票的原因是什么? – Sumeet

0

我认为有2个错误,你已经做 1.适用于(I;我< copy.mLength;我++){ mString [I] = copy.mString [I];你不得不提,循环将开始。 2.mString = new char [copy.mLength + 1]; mString [i] ='\ 0'; 我想,你有答案:)