簡體   English   中英

C ++ std :: move意外行為(用於智能指針時移動字符串)

[英]C++ std::move unexpected behaviour (moving string when intended for smart pointer)

當我將字符串文字傳遞給動態分配的unique_ptr並存儲在vector中時(使用std :: move,因為顯然沒有其他方法),提取字符串時我得到一個奇數的返回值-它似乎已被剪切/移動。

#include <iostream>
#include <vector>
#include <memory>

class Something {
private:
    const char* name;
public:
    Something(const char* name) {
        this->name = name;
    }

    void printDetails() {
        std::cout << this->name << std::endl;
    }
};

int main()
{
    std::vector<std::unique_ptr<Something>> stuff;

    for(int i = 0; i < 10; i++) {
        std::unique_ptr<Something> thing(new Something("A nice fun string" + i));
        stuff.push_back(std::move(thing));
    }

    for(uint i = 0; i < stuff.size(); i++) {
        stuff[i]->printDetails();
    }

    return 0;
}

輸出:

A nice fun string
 nice fun string
nice fun string
ice fun string
ce fun string
e fun string
 fun string
fun string
un string
n string

它沒有動。 "ABC"是字符串文字,實際上只是一個指針char const * 加整數只會使整數向前移動,因此"ABC" + 1作用類似於"BC"

C風格的字符串文字只是char數組,當您訪問它們的內容時,數組只是它們第一個元素的指針。 因此,將此指針添加為整數將用作數組的后綴。

您想要的可能是連接您的文字和整數,在C ++中並不是那么容易。 使用C ++ 11的最快方法看起來很糟糕:

string("ABC") + to_string(i)

並且,如果您最后確實想要char * ,請復制該字符串的結果字符串( 在此處進行了詳細說明

(string("ABC") + to_string(i)).c_str()

這部分導致錯誤:

("A nice fun string" + i) 

我必須是char或char *本身,您正在通過i增加“一個不錯的字符串”的索引。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM