1

This seems simple to me but I'm having trouble actually finding anything explicitly stating this.

Does std::string stringArray[3] not create an array of std::string objects, the way that SomeType typeArray[3] would? The actual number is irrelevant; I just picked 3 arbitrarily.

In the Visual Studio 2010 debugger, it appears to create a single string as opposed to an array of strings. Why?

Wild guess: is it calling the default std::string constructor, and then invoking an unused access of index 3? If so, why doesn't that cause an out of bounds exception on an empty string?

Does this have something to do with overloading the [] operator?

There are plenty of ways to code the same things without specifically using an array of std::string without issue, but what is the explanation/justification for this behavior? It seems counterintuitive to me.

Edit: I found this thread std::string Array Element Access in which the comments on the answer appear to observe the same behavior.

4

4 に答える 4

6

Visual Studio のデバッガーは、多くの場合、配列またはポインターが指す最初のものだけを表示します。stringArray[1] stringArray[2]それよりも遠くを見るには、 etc を使用する必要があります。

于 2012-11-03T00:31:47.627 に答える
4

OPは彼の心を失っていません。しかし、VisualStudioの統合デバッガーは確かにそうです。これは、の演算子[]の検出の失敗だと思いますがstd::string、これは悲しいことですが、std::vector<std::string>

ウォッチウィンドウを使用してこれを回避する方法([自動]または[ローカル]ウィンドウafaikを使用してこれを行う方法はありません)の優れたリファレンスは、以前に投稿されたこの質問にあります。これは、ポインタベースの動的配列(で割り当てられた配列Type *p = new Type[n];)を表示するための非常に便利な方法でもあります。ヒント: " varname,n"を使用します。ここvarnameで、は変数(ポインターまたは固定配列)であり、' n'は展開する要素の数です。

デモンストレーションは、宣言されたC配列std::stringと、OPが監視していたstd::vector<std::string>ものを示し、次のように表示するためのものです。

int main(int argc, char *argv[])
{
    std::string stringArray[3];
    std::vector<std::string> vecStrings(3);
    return 0; // set bp *here*
}

ここに画像の説明を入力してください

于 2012-11-03T00:38:46.293 に答える
2

配列を作成します。何か違うものをコンパイルしたか、結果を誤って解釈しました。

次のコンテキストでは配列を作成しません。

void function(std::string stringArray[3]) { }

この関数パラメータは へのポインタstd::stringです。配列型の関数パラメータは使用できません。

extern std::string strnigArray[3];

これは配列を宣言しますが、定義しません。プログラム呼び出しのどこかに 3 つの文字列の配列があることをコンパイラに伝えますが、stringArray実際には作成しません。

それ以外の場合は、3 つの文字列の配列を作成します。

次の方法で確認できます。

assert( sizeof(stringArray) == 3*sizeof(std::string) );

またはC++ 11で

static_assert( sizeof(stringArray) == 3*sizeof(std::string), "three strings" );
于 2012-11-03T00:29:33.673 に答える
0

ええ、VS 2010 のデバッガーはここではうまく機能しませんが、他の人が言っているように、デバッガーの表示の問題に過ぎず、期待どおりに動作します。

VS 2012では、彼らははるかに優れた仕事をしました:-

ここに画像の説明を入力

于 2012-11-03T10:32:40.230 に答える